package test_try;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化和反序列化案例
 *
 * @author chendikai
 * @date 2022-10-18 10:21
 */
public class SerializableDemo {
    public static void main(String[] args) {
        String fileName = "E:" + File.separator + "DingLi" + File.separator
                + "class1314" + File.separator + "chendikai.txt";
        File file = new File(fileName);

        // 序列化
        try {
            // 获取对象输出流，目的：将对象信息进行序列化后保存或进行网络传输
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));

            Person person_zhang = new Person("zhangsan", 18);
            objectOutputStream.writeObject(person_zhang);

            System.out.println("对象信息保存成功......");
            objectOutputStream.flush();
            objectOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 反序列化
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file));

            Person person_read = (Person) objectInputStream.readObject();

            System.out.println("反序列化后的对象信息：" + person_read.getName() + "==>" + person_read.getAge());

            objectInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
